require "Common/define"
require "Logic/Config"
require "Common/functions"

UIRookieGuide = {}
HelperFunc.SetUIEnv(UIRookieGuide)
local this = UIRookieGuide;

this.LuaBehaviour = nil;
this.transform = nil;
this.gameObject = nil;
this.hasInit = nil;

this.textinfo = nil; --文字描述引导
this.guideman = nil;  --人物例会
this.btnPoint = nil; --小箭头手指
this.btn_jump = nil; --跳过按钮
this.panelChat = nil;
this.hasInit = false;


this.objEffect = nil;
this.effectWrap = nil
this.chatController = nil;
this.pointController = nil;
this.jumpController = nil;
this.bgController = nil;
this.manController = nil;
this.guideHolder = nil;
this.showSmallBtnCtrl = nil
this.smallButton = nil
this.fullscreenBtn = nil
---@type GuideMgr
local mgr = nil
function UIRookieGuide.Init(data)
    local name,packageName = getUIName(PanelNames.UIRookieGuide);
    panelMgr:Push(name, packageName,this.OnCreate, Config.useLocalUI);
    --panelMgr:ShowUI(name, this.onCreate,Config.useLocalUI);
end

function UIRookieGuide.OnCreate(obj)
    gameObject = obj;
    -- transform =gameObject.transform;
    if not hasInit then
        this.clickCount = 0
        this.clickGuideId = 0
        this.preAudioName = ""
        hasInit = true;
        mgr = logicMgr.GuideMgr
        panelChat = obj:GetChild("panelChat");
        chatController = obj:GetController("showChat");
        textinfo = panelChat:GetChild("title");
        smallButton = obj:GetChild("button")
        btnPoint = obj:GetChild("btnPoint");
        Util.SetOrderType(btnPoint.displayObject.gameObject,"mapBeijing");
        pointController = obj:GetController("showPoint");
        showSmallBtnCtrl = obj:GetController("showSmallBtn")
        btn_jump = obj:GetChild("btn_jump");
        jumpController = obj:GetController("showJump");
        fullscreenBtn = obj:GetChild("fullscreen")
        guideHolder = obj:GetChild("guideHolder");
        guideman = obj:GetChild("guideman");
        manController = obj:GetController("showMan");

        bgController = obj:GetController("showBg");
        effectWrap = GoWrapper.New();
        this.addEvent();
        this.touchBtnPos = Vector2.zero
        local width,height = this.GetScreenWH()
        this.fullscreenBtn.width = width
        this.fullscreenBtn.height = height
        this.fullscreenBtn:SetXY(0,0)
        this.isReceivedGuideLevelUp = false
    end

    this.hideUI();
    this.GuideEnterTrigger()
end
function UIRookieGuide.GetScreenWH()
    local width = 1080
    --local height = 1920
    local height = Screen.height/Screen.width * 1080
    if height < 1920 then
        height = 1920
    end
    --[[if Screen.width > width then
        width = Screen.width
    end
    if Screen.height > height then
        height = Screen.height
    end]]
    return width,height
end
function UIRookieGuide.SetGuideUI()
    local NowGuide = mgr.GetNowGuideCfg()
    if NowGuide == nil then return end
    bgController.selectedIndex = NowGuide.f_Shade;

    if NowGuide.f_OperateType == 0 then
        showSmallBtnCtrl.selectedIndex = 0
    elseif NowGuide.f_OperateType == 1 then
        showSmallBtnCtrl.selectedIndex = 0
    else
        showSmallBtnCtrl.selectedIndex = 1
    end
    if string.IsNilOrEmpty(NowGuide.f_ArrowShift) or NowGuide.f_OperateType == 0 then
        pointController.selectedIndex = 0
    else
        pointController.selectedIndex = 1
        this.RefreshArrowPos()
    end
    if (NowGuide.f_Skip == 1) then
        jumpController.selectedIndex = 1;
    else
        jumpController.selectedIndex = 0;
        if (NowGuide.f_SkipLocation ~= "") then
            local SkipLocation = NowGuide.f_SkipLocation
            btn_jump:SetXY(SkipLocation[1], SkipLocation[2]);
        end
    end

    textinfo.text = getLanguage(NowGuide.f_GuideText);
    if (NowGuide.f_GuideEffect ~= "") then
        resMgr:LoadPrefab(NowGuide.f_GuideEffect, function(go)
            if objEffect then
                destroy(objEffect)
            end
            objEffect = newObject(go)
            objEffect:AddComponent(TCanvas)
            objEffect:AddComponent(TChangeSortingOrder)
            effectWrap.wrapTarget = objEffect
            guideHolder:SetNativeObject(effectWrap);
            this.RefreshEffectPos(this.IsFullScreen())
            Util.Lua_SetLocalPositionXYZ(objEffect.transform,0,0,0)
        end);
    end
end

function UIRookieGuide.ClickGuide(evt)
    if this.isReceivedGuideLevelUp then -- level up long touch
        this.isReceivedGuideLevelUp = false
        return
    end
    if not this.isAlwaysLevelUp then
        if not mgr.EnableClick() then
            log("DisableClick")
            return
        end
        if this.clickGuideId ~= mgr.GetGuideID() then
            this.clickCount = 1
            this.clickGuideId = mgr.GetGuideID()
        else
            this.clickCount = this.clickCount + 1
        end
        if this.clickCount >= 3 then
            logError("点击次数超过3次，跳过引导："..mgr.GetGuideID())
            mgr.EndCurGuide(mgr.GetNowGuideCfg())
            return
        end
    end
    mgr.ClickTouchButton(evt)
    mgr.ResetClick()
    if this.isAlwaysLevelUp then
        return
    end
    if this.isReceivedGuideLevelUp then -- level up short touch
        this.isReceivedGuideLevelUp = false
        return
    end
    this.StartNextGuide()
end

function UIRookieGuide.TouchSmallBtnBegin()
    mgr.TouchBeginEffect()
    local cfg = mgr.GetNowGuideCfg()
    if not string.IsNilOrEmpty(cfg.f_OperateParm3) then
        local tb = decodeJsonStrToTabel(cfg.f_OperateParm3)
        if mgr.IsNeedTouch(tb[1]) then--长按
            pointController.selectedIndex = 0
            mgr.touchBegin()
            return
        end
    end
    local type,start,_end = mgr.DecodeCurOperateParam2()
    if type == mgr.OPERATE_PARAM2.drag then
        log("drag Begin")
        this.ignoreUpdatePos = true
    end
    FireEvent(Config.EventType.GuideTeamRoleTouch,"begin",start)
end

function UIRookieGuide.TouchSmallBtnEnd()
    mgr.TouchEndEffect()
    local cfg = mgr.GetNowGuideCfg()
    if not string.IsNilOrEmpty(cfg.f_OperateParm3) then
        local tb = decodeJsonStrToTabel(cfg.f_OperateParm3)
        if mgr.IsNeedTouch(tb[1]) then--长按
            mgr.touchEnd()
            return
        end
    end
    local type,start,_end = mgr.DecodeCurOperateParam2()
    if type == mgr.OPERATE_PARAM2.drag then
        log("drag end")
        FireEvent(Config.EventType.GuideTeamRoleTouch,"end",start,_end)
    end
end

function UIRookieGuide.ClickBtBGGuide()
    smallButton.onClick:Remove(this.ClickBtBGGuide)
    smallButton.visible = false
    this.StartNextGuide();
end

function UIRookieGuide.StartNextGuide()
    if this.isAlwaysLevelUp then
        return
    end
    mgr.HighlightObj(false)
    if mgr.waitingMsgId > 0 then
        log("[引导]等待消息:"..mgr.waitingMsgId)
        mgr.ResetClick(2)
        return
    end
    this.GuideWaitingMsgCallback()
    mgr.StartNextGuide()
end

function UIRookieGuide.JumpThisTrigger()
    this.GuideForceEnd();
    mgr.SkipThisTrigger()
end
function UIRookieGuide.ClickFullScreen()
    local cfg = mgr.GetNowGuideCfg()
    if not cfg then return end
    log("[ClickFullScreen] step: "..cfg.f_GuideStepId)
end
function UIRookieGuide.GuideForceEnd()
    this.hideUI(true);
end
function UIRookieGuide.GuideTeamRoleTouchSuc()
    this.ignoreUpdatePos = false
    CloseEvent(Config.EventType.GuideTeamRoleTouchSuc,this.GuideTeamRoleTouchSuc)
    smallButton.onTouchBegin:Remove(this.TouchSmallBtnBegin)
    smallButton.onTouchEnd:Remove(this.TouchSmallBtnEnd)
    smallButton.visible = false
    this.StartNextGuide()
end
function UIRookieGuide.GuidePause(pause)
    this.gameObject.visible = not pause
end
function UIRookieGuide.GuideEnterTrigger()
    print("GuideEnterTrigger",mgr.GetGuideID())
    local sendGuide = mgr.GetNowGuideCfg()
    if sendGuide == nil then return end
    if (sendGuide.f_GuideChara ~= "") then
        resMgr:LoadSpritePrefab(sendGuide.f_GuideChara, function(sp)
            guideman.texture = NTexture.New(sp.texture);
        end);
    end
    AudioManager.Stop(this.preAudioName, nil, AudioManager.WwiseFlagEnum.Voice)
    this.preAudioName  = AudioManager.Play(sendGuide.f_Voice)
    gameObject.visible = true ;
    --按钮区域
    if (sendGuide.f_OperateType == 1) then
        if mgr.HasTouchButton() then
            smallButton.onClick:Clear()
            smallButton.onClick:Add(this.ClickGuide)
        end
    end
    --任意区域
    if (sendGuide.f_OperateType == 0) then
        smallButton.onClick:Clear()
        smallButton.onClick:Add(this.ClickBtBGGuide)
    end
    if sendGuide.f_OperateType == 2 then
        ListenEvent(Config.EventType.GuideTeamRoleTouchSuc,this.GuideTeamRoleTouchSuc)
    end
    smallButton.onTouchBegin:Clear()
    smallButton.onTouchBegin:Add(this.TouchSmallBtnBegin)
    smallButton.onTouchEnd:Clear()
    smallButton.onTouchEnd:Add(this.TouchSmallBtnEnd)
    this.isAlwaysLevelUp = false
    if not string.IsNilOrEmpty(sendGuide.f_OperateParm3) then
        local tb = decodeJsonStrToTabel(sendGuide.f_OperateParm3)
        if mgr.IsNeedTouch(tb[1]) then --长按
            this.isAlwaysLevelUp = tb[1] == mgr.OPERATE_PARAM3.alwaysLevelUp
            if this.isAlwaysLevelUp then
                ListenEvent(Config.EventType.GuideLevelUp,this.GuideLevelUpReceived)
            end
        end
    end
    local touchBtn = mgr.GetButton()
    smallButton.visible = true
    fullscreenBtn.visible = true
    local isFullScreenClick = this.IsFullScreen()
    if isFullScreenClick then
        local w,h = this.GetScreenWH()
        smallButton.width = w
        smallButton.height = h
        smallButton:SetXY(0,0)
        if Config.DEBUG_GUIDE then
            smallButton.icon = "ui://CommonUI/quality_whitebg"
            smallButton.alpha = 0.5
        end
    else
        local type,w,h = mgr.DecodeCurOperateParam3()
        if type ~= mgr.OPERATE_PARAM3.widgetSize then
            w = touchBtn.width
            h = touchBtn.height
        end
        local x,y = mgr.GetTouchBtnPos(smallButton,w,h)
        smallButton.width = w
        smallButton.height = h
        smallButton:SetXY(x,y)
        if Config.DEBUG_GUIDE then
            smallButton.icon = "ui://CommonUI/common_frame_icon_choose"
        end
    end
    if sendGuide.f_Delayed < 0.2 then
        sendGuide.f_Delayed = 0.2
    end
    if sendGuide.f_Delayed > 0.01 then
        smallButton.visible = false
        chatController.selectedIndex = 0
        manController.selectedIndex = 0
        utimer.delayCall(this.DelayShow,sendGuide.f_Delayed*1000)
    else
        this.RefreshChat(isFullScreenClick)
        this.SetGuideUI();
    end
end
function UIRookieGuide.DelayShow()
    if smallButton then
        smallButton.visible = true
        this.RefreshChat(this.IsFullScreen())
        this.SetGuideUI();
    end
end
function UIRookieGuide.RefreshChat(isFullScreen)
    local NowGuide = mgr.GetNowGuideCfg()
    if (NowGuide.f_GuideBoxLocation ~= "") then
        chatController.selectedIndex = 1;
        manController.selectedIndex = 1;
    end
    this.RefreshChatPos(isFullScreen)
end
function UIRookieGuide.RefreshChatPos(isFullScreen)
    local NowGuide = mgr.GetNowGuideCfg()
    if (NowGuide.f_GuideBoxLocation ~= "") then
        local pos = NowGuide.f_GuideBoxLocation
        isFullScreen = isFullScreen or this.IsPosHalfScreen()
        local x,y = this.GetAnchorPos(isFullScreen)
        panelChat:SetXY(pos[1] + x, pos[2]+y);
        guideman:SetXY(pos[1] + x-40, pos[2]+y-550);
    end
end
function UIRookieGuide.IsPosHalfScreen()
    local NowGuide = mgr.GetNowGuideCfg()
    if NowGuide and NowGuide.f_ScreenCenter == 1 then
        return true
    end
    return false
end
function UIRookieGuide.IsFullScreen()
    local NowGuide = mgr.GetNowGuideCfg()
    local touchBtn = mgr.GetButton()
    if not NowGuide then return true end
    if NowGuide.f_OperateType == 0 or not touchBtn then
        return true
    else
        return false
    end
end
function UIRookieGuide.GuideNetReconnect(startReconnect)
    if not mgr.IsGuiding() then
        return
    end
    if startReconnect then
        mgr.HighlightObj(false)
        Util.SetOrderType(btnPoint.displayObject.gameObject,"Default");
       -- this.smallButton.visible = false
    else
        mgr.HighlightObj(true)
        Util.SetOrderType(btnPoint.displayObject.gameObject,"mapBeijing");
        --this.smallButton.visible = true
    end
end
function UIRookieGuide.GuideWaitingMsgCallback()
    this.hideUI();
    destroy(objEffect);
    objEffect = nil;
end
function UIRookieGuide.GuideUpdatePos()
    if this.ignoreUpdatePos then return end
    local x,y = mgr.GetTouchBtnPos(smallButton,smallButton.width,smallButton.height)
    if math.abs(x - this.touchBtnPos.x) < 0.01 and math.abs(y - this.touchBtnPos.y) < 0.01 then
        return
    end
    this.touchBtnPos:Set(x,y)
    smallButton:SetXY(x,y)
    local isFull = this.IsFullScreen()
    this.RefreshArrowPos(isFull)
    this.RefreshChatPos(isFull)
    this.RefreshEffectPos()
end
function UIRookieGuide.GetAnchorPos(isFullScreen)
    local x = 0
    local y = 0
    if isFullScreen then
        x,y = this.GetScreenWH()
        --Screen.width/2
        --y = Screen.height/2
        x = x/2
        y = y/2
    else
        x,y = mgr.GetBtnRootPos(btnPoint)
    end
    return x,y
end
function UIRookieGuide.RefreshArrowPos(isFullScreen)
    if pointController.selectedIndex ~= 1 then return end
    local NowGuide = mgr.GetNowGuideCfg()
    local ArrowPos=NowGuide.f_ArrowShift
    local x,y = this.GetAnchorPos(isFullScreen)
    btnPoint:SetXY(x+tonumber(ArrowPos[1]),y+tonumber(ArrowPos[2]));
end
function UIRookieGuide.RefreshEffectPos()
    local NowGuide = mgr.GetNowGuideCfg()
    if NowGuide.f_GuideEffect == "" then return end
    local pos = NowGuide.f_GuideEffectLocation
    local x,y = this.GetAnchorPos(false)
    guideHolder:SetXY(pos[1] + x, pos[2]+ y)
end
function UIRookieGuide.GuideLevelUpReceived(hasEnough, level)
    if this.isAlwaysLevelUp then
        local type,param = mgr.DecodeOperateParam3(mgr.GetNowGuideCfg())
        if type == mgr.OPERATE_PARAM3.alwaysLevelUp then
            if level and level >= param or not hasEnough then
                this.isAlwaysLevelUp = false
                this.isReceivedGuideLevelUp = true
                CloseEvent(Config.EventType.GuideLevelUp,this.GuideLevelUpReceived)
                mgr.ResetClick()
                this.StartNextGuide()
                FireEvent(Config.EventType.GuideLevelUpStop)
            end
        end
    end
end
function UIRookieGuide.GuideShowFullscreenMask()
    this.fullscreenBtn.visible = true
end
function UIRookieGuide.hideUI(includeFull)
    bgController.selectedIndex = 0;
    jumpController.selectedIndex = 0;
    chatController.selectedIndex = 0;
    manController.selectedIndex = 0;
    pointController.selectedIndex = 0;
    if includeFull then
        this.fullscreenBtn.visible = false
    else
        this.fullscreenBtn.visible = true
    end
    this.touchBtnPos:Set(0,0)
    this.smallButton.onClick:Clear()
    this.smallButton.onTouchBegin:Clear()
    this.smallButton.onTouchEnd:Clear()
    this.smallButton.visible = false
end

function UIRookieGuide.addEvent()
    btn_jump.onClick:Add( this.JumpThisTrigger);
    fullscreenBtn.onClick:Add(this.ClickFullScreen)
    ListenEvent(Config.EventType.GuideForceEnd,this.GuideForceEnd)
    ListenEvent(Config.EventType.GuideEnterTrigger,this.GuideEnterTrigger)
    ListenEvent(Config.EventType.GuidePause,this.GuidePause)
    ListenEvent(Config.EventType.GuideUpdatePos,this.GuideUpdatePos)
    ListenEvent(Config.EventType.GuideNetReconnect,this.GuideNetReconnect)
    ListenEvent(Config.EventType.GuideWaitingMsgCallback,this.GuideWaitingMsgCallback)
    ListenEvent(Config.EventType.GuideShowFullscreenMask,this.GuideShowFullscreenMask)
end

function UIRookieGuide.removeEvent()
    btn_jump.onClick:Remove(this.JumpThisTrigger);
    fullscreenBtn.onClick:Clear()
    CloseEvent(Config.EventType.GuideForceEnd,this.GuideForceEnd)
    CloseEvent(Config.EventType.GuideEnterTrigger,this.GuideEnterTrigger)
    CloseEvent(Config.EventType.GuideTeamRoleTouchSuc,this.GuideTeamRoleTouchSuc)
    CloseEvent(Config.EventType.GuidePause,this.GuidePause)
    CloseEvent(Config.EventType.GuideUpdatePos,this.GuideUpdatePos)
    CloseEvent(Config.EventType.GuideNetReconnect,this.GuideNetReconnect)
    CloseEvent(Config.EventType.GuideWaitingMsgCallback,this.GuideWaitingMsgCallback)
    CloseEvent(Config.EventType.GuideShowFullscreenMask,this.GuideShowFullscreenMask)
end

function UIRookieGuide.OnDestroy()
    this.removeEvent();
    destroy(this.objEffect)
    this.objEffect = nil
    if effectWrap then
        effectWrap:Dispose()
        effectWrap = nil
    end
end

function UIRookieGuide.OnEnable()

end

function UIRookieGuide.OnDisable()

end

return UIRookieGuide;
